package com.nw.dsl4j;

import java.net.URL;
import java.net.URLClassLoader;
import java.text.MessageFormat;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;

import com.nw.dsl4j.generator.Generator;


public class Dsl4jGenerator {
	private static Options options;

	public static void main(String[] args) {
		prepareOptions();
		CommandLineParser parser = new GnuParser();
		CommandLine cmd = null;
		try {
			 cmd = parser.parse( options, args);
		} catch (ParseException e) {
			System.out.println("Error parsing command line: " + e.getMessage());
			showHelp();
			return;
		}
		if (cmd.hasOption("h")) {
			showHelp();
			return;
		}

		String target = cmd.getOptionValue("t", ".");
		String grammar = cmd.getOptionValue("g", ".");
		String classPath = cmd.getOptionValue("c", ".");
		String[] classes = cmd.getArgs();
		for (String cls : classes) {
			 System.out.println(MessageFormat.format(
				     "Generating dsl for class: {0}. Java source files go to {1} and antlr grammar file go to {2}",
				     cls, target, grammar));
			generate(cls, target, grammar, classPath);
		}
		if (classes.length == 0) showHelp();
		
	}
	public static void generate(String className, String target, String grammar, String classesFolder) {
		try {
			URLClassLoader classLoader = 
				new URLClassLoader(new URL[] { new URL("file:" + classesFolder) }, 
									Thread.currentThread().getContextClassLoader());

			Generator generator = new Generator(className, target, grammar, classLoader);
			generator.generate();

			System.out.println("done");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void prepareOptions() {
		options = new Options();
		
		Option target = new Option("t", "target", true, "destination of generated java source files");
		target.setRequired(false);
		target.setArgs(1);
		target.setOptionalArg(false);
		options.addOption(target);

		Option grammar = new Option("g", "grammar", true, "destination of generated grammar file");
		grammar.setRequired(false);
		grammar.setArgs(1);
		grammar.setOptionalArg(false);
		options.addOption(grammar);
		
		Option classesDir= new Option("c", "classes", true, "Class path");
		options.addOption(classesDir);

		Option verbose = new Option("v", "verbose", true, "print additional debug info");
		options.addOption(verbose);
		
		Option help = new Option("h", "help", false, "print this help");
		options.addOption(help);
		
	}

	private static void showHelp() {
		HelpFormatter formatter = new HelpFormatter();
		formatter.printHelp( Dsl4jGenerator.class.getCanonicalName() + " [options] dslClassName1 ...  ", options);		
	}
}
